<?php

class SubcertController extends Controller {
    const PAGE_SIZE=10;

    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction='create';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
        'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
        array('allow',  // allow all users to perform 'list' and 'show' actions
        'actions'=>array('list','show','view'),
        'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('create','update','ListChooseGrid'),
        'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
        'actions'=>array('admin','delete'),
        'users'=>array('admin'),
        ),
        array('deny',  // deny all users
        'users'=>array('*'),
        ),
        );
    }

    /**
     * Shows a particular model.
     */
    public function actionShow() {
        Yii::app()->format->dateFormat = 'd/m/Y';
        
        $rows = array(
            'out_permit',
            array(
            'name'=>'etd',
            'type'=>'date',
            ),
            'awb',
            'vessel',
            'remark:html',
        );
        $model = $this->loadsubcert();
        $export_info = $this->renderPartial('../detailview/default', array('model'=>$model,'rows'=>$rows), true);
        $this->render('show',array('export_info'=>$export_info,'shipment'=>$this->makeListView($model->id)));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate() {
        $model=new subcert;
        $items = array();
        $s=isset($_GET['s'])?$_GET['s']:'';
        //$rm=isset($_GET['rm'])?$_GET['rm']:'';//(isset($_POST['Choose_DO_Container_items']))?$_POST['Choose_DO_Container_items']:'';
        if(isset($_GET['rm']))
            $rm = $_GET['rm'];
        elseif(isset($_POST['Choose_DO_Container_items']))
            $rm = $_POST['Choose_DO_Container_items'];
        else
            $rm = '';
        $data = $this->ListChooseGrid($s,$rm);
        $form = new CForm("application.views.subcert.subcert_form",$model);
        $form->attributes['class'] = 'yiiForm';
        $items = isset($_POST['Choose_DO_Container_items'])?$_POST['Choose_DO_Container_items']:array();
        $_items = array();
        foreach($items as $value)
            $_items[$value] = cargo::model()->findByPk($value)->ref_no;
        $items = $_items;
        $model->cargo_details = $items;
        if($form->submitted('add') && $form->validate()) {
            if($model->save(false)) {
                //$this->redirect(array('show','id'=>$model->id));
            }
        }
        $this->render('create',array('form'=>$form,'gridView'=>$data,'items'=>$items));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate() {
        $model=$this->loadsubcert();
        if(isset($_POST['subcert'])) {
            $model->attributes=$_POST['subcert'];
            if($model->save())
                $this->redirect(array('show','id'=>$model->id));
        }
        $this->render('update',array('model'=>$model));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
        // we only allow deletion via POST request
            $this->loadsubcert()->delete();
            $this->redirect(array('list'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionList() {
        $criteria=new CDbCriteria;

        $pages=new CPagination(subcert::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $models=subcert::model()->findAll($criteria);

        $this->render('list',array(
            'models'=>$models,
            'pages'=>$pages,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $this->processAdminCommand();

        $criteria=new CDbCriteria;

        $pages=new CPagination(subcert::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort=new CSort('subcert');
        $sort->applyOrder($criteria);

        $models=subcert::model()->findAll($criteria);

        $this->render('admin',array(
            'models'=>$models,
            'pages'=>$pages,
            'sort'=>$sort,
        ));
    }

    /**
     * List items for listview
     */
     public function makeListView($id,$display=null) {
         if($id===null || $id == '')
            return false;
         $criteria = new CDbCriteria;
         $criteria->addColumnCondition(array('subcert_id'=>$id));
         $criteria->with = array('cargo'=>array('with'=>array('customer','consignee')));
         $criteria->limit = 10;
         $criteria->order = 't.ref_no';

         $data = new CActiveDataProvider('cargo',array(
                            'criteria'=>$criteria,
                            'pagination'=>array(
                                'pageSize'=>10,
                             ),
             ));
         return $this->renderPartial('listview/default', array('data'=>$data), true);
     }
    /**
     * List items for gridview
     */
    public function ListChooseGrid($search,$remove) {
        $cargo = !empty($_GET['db'])?$_GET['db']:true;
        if($cargo) {
            $criteria = new CDbCriteria();
            $sort = new CSort();
            if(!empty($search)) {
                $criteria->condition = 'consignee.cname like :search or customer.cname like :search or t.ref_no like :search';
                $criteria->params = array(':search'=>'%'.$search.'%');
            }
            if(!empty($remove)) {
                if(is_array($remove)) {
                    $i=0;
                    foreach($remove as $id) {
                        $criteria->addCondition('t.id <> :id'.$i);
                        $criteria->params[':id'.$i] = $id;
                        $i++;
                    }
                }
                else {
                    $criteria->addCondition('t.id <> :id');
                    $criteria->params[':id'] = $remove;
                }
            }

            //$criteria->with = array('cargo'=>array('with'=>array('customer','consignee')));
            $criteria->limit = 20;
            //--
            $sort->defaultOrder = 't.in_date desc';
            $sort->params = array('db'=>0);
            $sort->attributes = array(
                'date'=>array('label'=>'Arrival Date','asc'=>'in_date','desc'=>'in_date desc'),
                'ship_ref'=>array('label'=>'Shipping Ref','asc'=>'cargo.ref_no','desc'=>'cargo.ref_no desc'),
                'customer'=>array('label'=>'Shipper','asc'=>'customer.cname','desc'=>'customer.cname desc'),
                'consignee'=>array('label'=>'Consignee','asc'=>'consignee.cname','desc'=>'consignee.cname desc'),
            );
            $dataProvider=new CActiveDataProvider('cargo', array(
                'criteria'=>$criteria,
                'pagination'=>array(
                'pageSize'=>15,
                ),
                'sort'=>$sort,
            ));
            $columns = array(
                array('name'=>'id','value'=>'$data->id.";".$data->ref_no','class'=>'CCheckBoxColumn'),
                array('name'=>'date','value'=>'date("d/m/y",$data->in_date)'),
                array('name'=>'ship_ref','value'=>'$data->ref_no'),
                array('name'=>'customer','value'=>'$data->shipper->cname'),
                array('name'=>'consignee','value'=>'$data->consignee->cname'),
                array('name'=>'invoice','value'=>'$data->invoice->ref_no'),
                array('name'=>'amount','value'=>'$data->cur[$data->currency]." $".number_format($data->amt,2,".",",")'),
            );
        }
        return $this->renderPartial('../gridview/subcertChooseDO', array('data'=>$dataProvider,'columns'=>$columns), true);
    }
    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadsubcert($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=subcert::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadsubcert($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
    public function actionview() {
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'A4', true, 'UTF-8', false);

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor(Yii::app()->params['company']['name']);
        $pdf->SetTitle('TCPDF Example 048');
        $pdf->SetSubject('Subcert of '.Yii::app()->params['company']['name']);
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
        $pdf->setPrintFooter(false);
        $pdf->setPrintHeader(false);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);

        //$pdf->setLanguageArray($l);
        $pdf->AddPage();

        // set font
        $pdf->SetFont('helvetica', '', 8);

        $tbl = $this->renderPartial('../report/task_report', array(), true);

        $pdf->writeHTML($tbl, true, false, false, false, '');

        //Close and output PDF document
        $pdf->Output('example_048.pdf', 'I');
    }
}
